import { useState, useCallback } from 'react';
import { Message } from '@arco-design/web-react';
export default function useFetchData(fetchData, initialParams) {
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState({
    pageSize: 10,
    current: 1,
    total: 0,
    // sizeCanChange: true,
    showTotal: true,
    // pageSizeChangeResetCurrent: true,
    showJumper: true,
  });

  const [loading, setLoading] = useState(false);

  const getData = useCallback(
    async (searchParams = initialParams) => {
      const { PageIndex, ...restSearchParams } = searchParams;

      try {
        const { type, ...restSearchParams } = searchParams;
        const obj = {
          PageIndex: pagination.current,
          PageSize: pagination.pageSize,
          ...restSearchParams,
        };

        setLoading(true);

        const res = await fetchData({ ...obj });

        setData(res.Result.Datas); // res.Result.Datas是数组
        setPagination({
          ...pagination,
          total: res.Result.TotalCount, // res.Result.TotalCount是总条数
          current: searchParams.PageIndex ? searchParams.PageIndex : 1,
          ...restSearchParams,
        });

        setLoading(false);
      } catch (error) {
        setLoading(false);
        Message.error('列表获取失败，请刷新重试');
      }
    },
    [fetchData, pagination, initialParams]
  );

  return { data, pagination, loading, getData, setData };
}
